package com.example.playaudiotest

import android.media.MediaPlayer
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() , View.OnClickListener{
    private val mediaPlayer = MediaPlayer();

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initMediaPlayer()
        play.setOnClickListener(this);
        pause.setOnClickListener(this);
        stop.setOnClickListener(this);
    }



    override fun onClick(v: View?) {
        when(v?.id){
            R.id.play -> {
                if(!mediaPlayer.isPlaying){
                    mediaPlayer.start()
                }
            }
            R.id.pause -> {
                if(mediaPlayer.isPlaying){
                   mediaPlayer.pause()
                }
            }
            R.id.stop  -> {
                if(mediaPlayer.isPlaying){
                    mediaPlayer.reset()
                    initMediaPlayer()
                }
            }
        }
    }

    private fun initMediaPlayer(){
        val assetManager = assets;
        val fd = assetManager.openFd("music.mp3")
        mediaPlayer.setDataSource(fd.fileDescriptor,fd.startOffset,fd.length);
        mediaPlayer.prepare()
    }
}